package com.example.demo.interceptor;

import com.example.demo.Utils.Utils;
import com.example.demo.annotation.CurrentLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Lenovo
 * @description TODO
 * @createTime 2022/7/21 21:09
 */

public class CurrentLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            CurrentLimit methodAnnotation = handlerMethod.getMethodAnnotation(CurrentLimit.class);
            if (null == methodAnnotation){
                return true;
            }else {
                int maxCount = methodAnnotation.maxCount();
                int time = methodAnnotation.time();
                String key = request.getContextPath();
                Integer number = (Integer)redisTemplate.opsForValue().get(key);
                String ip = Utils.getIp(request);

                if (true){

                    return false;
                }else {
                    return true;
                }

            }

        }
        return true;
    }

}
